
#include <BFont>
#include <BStyle>
#include <BPainter>
#include <BFile>

#include "XmlFormat.h"
#include "TextEditor.h"

TextEditor::TextEditor(BWidget* parent) : BTextEdit(parent)
{
	this->setMargin(3);
	this->setLineSpacing(5);
}
TextEditor::~TextEditor()
{

}

bool TextEditor::loadFile(const BString& fileName)
{
	BString text;
	if (!BFile::Load(fileName, text))
	{
		BString message;
		message << "Load file failed : " << fileName;
		this->post("message", message);
		return false;
	}
	this->setText(text);
	this->setTitle(fileName.name());
	return true;
}
bool TextEditor::saveFile(const BString& fileName)
{
	const BString& text = this->text();
	if (!BFile::Save(fileName, text))
	{
		BString message;
		message << "Save file failed : " << fileName;
		this->post("message", message);
		return false;
	}
	return true;
}

void TextEditor::styleEvent(const BEvent& event)
{
	BTextEdit::styleEvent(event);
	const BStyle* style = event.value();
	BFont* font = (BFont*)this->realFont();
	font->setTabSize(2);
}
void TextEditor::freshEvent(const BEvent& event)
{
	BTextEdit::freshEvent(event);
	BString text = this->lineCount();
	BFont* font = (BFont*)this->realFont();
	int left = font->textSize(text).width() + 3;
	this->setPerch(Part_Left, left);
}
void TextEditor::paintEvent(const BEvent& event)
{
	BTextEdit::paintEvent(event);

	BRect leftRect = this->rect(Part_Left);
	BPainter painter(this);
	painter.setColor(Color_Text);
	BString lineText;
	const BIntArray& lines = this->query("visual-lines");
	for (int i = 0; i < lines.size(); i++)
	{
		int line = lines[i];
		if (!this->lineVisible(line))
			continue;
		BRect lineRect = this->lineRect(line);
		lineRect.left() = leftRect.left();
		lineRect.right() = leftRect.right();
		lineText.reset();
		lineText << line + 1;
		painter.drawText(lineRect, lineText, Align_RightCenter);
	}
}
